package com.hongxun.design.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.NavigationActivity;
import com.hongxun.design.activitys.SetPointInformationActivity;
import com.hongxun.design.bean.Exploration;
import com.hongxun.design.bean.SearchProjectBean;
import com.hongxun.design.bean.photopassbean.SystemTypeBean;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.IntentToActivity;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyDecimalFormat;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.pickerview.lib.DensityUtil;
import com.hongxun.design.ui.ui_map_icon.PointView;
import com.hongxun.design.utils.ActionSheetUtil;
import com.hongxun.design.utils.InputUtil;
import com.hongxun.design.utils.PopwindowUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringCodeTableUtil;
import com.hongxun.design.utils.imageutil.UriUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zerdoor_pc on 2016/5/6.
 */
public class MBaiduMap extends RelativeLayout {
    Context context;

    public MBaiduMap(Context context) {
        super(context);
        if (isInEditMode()) return;
        this.context = context;
    }

    public MBaiduMap(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (isInEditMode()) return;
        this.context = context;
    }

    public MBaiduMap(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        if (isInEditMode()) return;
        this.context = context;
    }

    TextView zoomin, zoomout;
    MapView mMapView;
    BaiduMap mBaiduMap;

    SimpleDraweeView satellite, position;
    boolean isstylesatellite;

    List<BitmapDescriptor> bitmaps = null;

    @Override
    protected void onFinishInflate() {
        position = (SimpleDraweeView) findViewById(R.id.position);
        zoomin = (TextView) findViewById(R.id.zoomin);
        zoomout = (TextView) findViewById(R.id.zoomout);
        satellite = (SimpleDraweeView) findViewById(R.id.satellite);
        mMapView = (MapView) findViewById(R.id.mapview);
        SetTypeface.set(zoomin, IconSourse.ADD);
        SetTypeface.set(zoomout, "—");
        mBaiduMap = mMapView.getMap();
        isstylesatellite = false;
        /**卫星图切换**/
        satellite.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isstylesatellite) {
                    isstylesatellite = false;
                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
                    ((SimpleDraweeView) view).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.style_satellite));
                } else {
                    isstylesatellite = true;
                    mBaiduMap.setMapType(BaiduMap.MAP_TYPE_SATELLITE);
                    ((SimpleDraweeView) view).setImageURI(UriUtil.getUri(MString.LOCALIMAGEHEAD + R.mipmap.style_map));
                }
            }
        });


        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(MyApp.zoom).build()));
        zoomin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                float zoomLevel = mBaiduMap.getMapStatus().zoom;
                MyLog.L(MString.SUCCESS + " zoomLevel=" + zoomLevel);
                if (zoomLevel <= 20) {
//					MapStatusUpdateFactory.zoomIn();
                    mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomIn());
                    zoomout.setEnabled(true);
                } else {
                    zoomin.setEnabled(false);
                    ToastShow.showShort(context, "已放大到最大");
                }
            }
        });
        zoomout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                float zoomLevel = mBaiduMap.getMapStatus().zoom;
                MyLog.L(MString.SUCCESS + " zoomLevel=" + zoomLevel);
                if (zoomLevel > 4) {
                    mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomOut());
                    zoomin.setEnabled(true);
                } else {
                    zoomout.setEnabled(false);
                    ToastShow.showShort(context, "已缩小到最小");
                }
            }
        });
        mMapView.showZoomControls(false);//隐藏缩放按钮
        mMapView.showScaleControl(true);//显示比例尺
        //SetOnMapStatusChangeListener();//加载拖拽监听
        bitmaps = new ArrayList<>();
        super.onFinishInflate();
    }


    public void setIsNewBlude() {

    }

    public void setNeedGps() {
    }

    public void setPositionClick(OnClickListener listener) {
        position.setOnClickListener(listener);
    }

    public void hidePosition() {
        position.setVisibility(GONE);
    }

    public MapView getMapView() {
        return mMapView;
    }

    public BaiduMap getBaiduMap() {
        return mBaiduMap;
    }

    public void setMarka(LatLng point) {
        if (point == null) return;
        mBaiduMap.clear();
        BitmapDescriptor b = BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_marka);
        mBaiduMap.addOverlay(new MarkerOptions().position(point)
                .icon(b));
        bitmaps.add(b);
//        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point));//将位置设为中心点
    }

    public Marker addMarka(LatLng point) {
        if (point == null) return null;
        BitmapDescriptor b = BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_marka);
        bitmaps.add(b);
        return (Marker) mBaiduMap.addOverlay(new MarkerOptions().position(point)
                .icon(b));

//        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point));//将位置设为中心点
    }

    public void setMarka(LatLng point, String no) {
        if (point == null) return;
//        mBaiduMap.clear();
//        mBaiduMap.addOverlay(new MarkerOptions().position(point).icon(BitmapDescriptorFactory.fromResource(0)));
//        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point));//将位置设为中心点
    }

    public Marker setMarka(LatLng point, int resource) {
        if (point == null) return null;
        mBaiduMap.clear();
        BitmapDescriptor b = BitmapDescriptorFactory
                .fromResource(resource);
        bitmaps.add(b);
        return (Marker) mBaiduMap.addOverlay(new MarkerOptions().position(point)
                .icon(b));
    }

    public void addMarka(LatLng point, int image) {
        if (point == null) return;
        BitmapDescriptor b = BitmapDescriptorFactory
                .fromResource(image);
        bitmaps.add(b);
        Marker m = (Marker) mBaiduMap.addOverlay(new MarkerOptions().position(point)
                .icon(b).anchor(0.5f, 0.5f));

    }

    public void addMarkacrcle(LatLng point, int image) {

        PointView textView = new PointView(context);
        textView.title.setVisibility(GONE);
        textView.title.setBackgroundResource(R.drawable.wihte_item);
        textView.setIcon(image, "");
        textView.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));


        if (point == null) return;
        BitmapDescriptor b = BitmapDescriptorFactory.fromView(textView);
        bitmaps.add(b);
        Marker m = (Marker) mBaiduMap.addOverlay(new MarkerOptions().position(point)
                .icon(b).anchor(0.5f, 0.5f));

    }


    List<Marker> markers = new ArrayList<>();


    /**
     * 项目地图点位*
     */
    @SuppressLint("NewApi")
    public void addMarka(final Context context, SearchProjectBean p, int image) {
        try {

            MyLog.L(MString.SUCCESSED + "p.getLat()=" + p.getLat() + "  p.getLng()=" + p.getLng());
            LatLng point = new LatLng(Double.parseDouble(p.getLat()), Double.parseDouble(p.getLng()));
            BitmapDescriptor b = BitmapDescriptorFactory.fromResource(image);
            bitmaps.add(b);
            OverlayOptions options = new MarkerOptions().position(point)
                    .icon(b);
            final Marker m = (Marker) mBaiduMap.addOverlay(options);
            m.setTitle(JSON.toJSONString(p));
            markers.add(m);
            TextView textView1 = new TextView(context);
            textView1.setText(" " + p.getProject_name() + " ");
//          textView1.setBackgroundResource(R.mipmap.popup);
            textView1.setBackgroundResource(R.mipmap.bg_wordsfordialog);
            textView1.setPadding(10, 10, 10, 0);
            textView1.setGravity(RelativeLayout.CENTER_VERTICAL);
            textView1.setBottom(DensityUtil.dip2px(context, 10));
            textView1.setTextColor(getResources().getColor(R.color.gray));
            final InfoWindow mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(textView1), point, -47, new InfoWindow.OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick() {
                    mBaiduMap.hideInfoWindow();
                    InputUtil.closeInput((Activity) context);
                    context.setTheme(R.style.ActionSheetStyleIOS7);
                    SearchProjectBean p = FastJsonUtil.JsonToGetSearchProject(m.getTitle());
                    String stage = p.getStage();
                    String stageids = p.getStage_ids();
                    if (stage.length() > 0) {
                        String[] stageName = stage.split(",");
                        String[] stageid = stageids.split(",");
                        List<SystemTypeBean> bean = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.designStage);
                        List<SystemTypeBean> mb = new ArrayList<SystemTypeBean>();
                        for (int i = 0; i < stageName.length; i++) {
                            for (SystemTypeBean s : bean) {
                                if (s.getTypecode().equals(stageName[i])) {
                                    mb.add(new SystemTypeBean(stageid[i], s.getTypename(), s.getTypecode()));
                                    break;
                                }
                            }
                        }
                        if (mb.size() > 0) {
                            ActionSheetUtil.openSheet((Activity) context, mb, m.getTitle());
                        } else {
                            ToastShow.showShort(context, "阶段不存在！");
                        }


                    }

                }
            });


            mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker marker) {
                    if (marker == m) {
                        mBaiduMap.showInfoWindow(mInfoWindow);
                    }
                    return true;
                }
            });
            mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
                public void onMapClick(LatLng point) {
                    mBaiduMap.hideInfoWindow();
                }

                public boolean onMapPoiClick(MapPoi poi) {
                    return false;
                }
            });
        } catch (Exception e) {

        }


    }

    List<Marker> marker_Seconds = new ArrayList<>();

    /**
     * 显示转角跳转*
     */
    public String projectType = "11";

    public void addMarka(Exploration exploration, final Context context, LatLng point, int image) {
        exploration.setIcon(image);
        String corner = exploration.corner;
        String number = exploration.number;
        PointView textView = new PointView(context);
        if (corner != null && corner.length() > 0 && Double.parseDouble(corner) != 0 && MyApp.isOnLine) {
            textView.setTitle(number + "(" + corner + "°)");
        } else {
            //textView.title.setVisibility(GONE);
            textView.setTitle(number);
        }
        textView.title.setBackgroundResource(R.drawable.wihte_item);
        textView.setIcon(image, "");
        textView.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        OverlayOptions options;
        BitmapDescriptor b = BitmapDescriptorFactory.fromView(textView);
        bitmaps.add(b);
        if (corner != null && corner.length() > 0) {
            options = new MarkerOptions().position(point)
                    .icon(b).anchor(0.5f, 0.7f);
        } else {
            options = new MarkerOptions().position(point)
                    .icon(b).anchor(0.5f, 0.5f);
        }
        Marker m = (Marker) mBaiduMap.addOverlay(options);
        m.setTitle(JSON.toJSONString(exploration));
        marker_Seconds.add(m);
    }

    /**
     * 点位无转角跳转*
     */
    public void addMarka(Exploration exploration, LatLng point, int image) {
        exploration.setIcon(image);
        if (point == null) return;
        PointView textView = new PointView(context);
        textView.title.setVisibility(GONE);
        textView.title.setBackgroundResource(R.drawable.wihte_item);
        textView.setIcon(image, "");
        textView.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        BitmapDescriptor b = BitmapDescriptorFactory.fromView(textView);
        bitmaps.add(b);
        OverlayOptions options = new MarkerOptions().position(point)
                .icon(b).anchor(0.5f, 0.5f);
        Marker m = (Marker) mBaiduMap.addOverlay(options);
        m.setTitle(JSON.toJSONString(exploration));
        marker_Seconds.add(m);

    }

    /**
     * 显示档距*
     */
    public void addMarka(final Context context, String distance, LatLng point) {

        OverlayOptions textOption = new TextOptions()
                .bgColor(getResources().getColor(R.color.white))
                .fontSize(com.hongxun.design.utils.DensityUtil.dip2px(context, 10))
                .fontColor(getResources().getColor(R.color.gray))
                .text(MyDecimalFormat.getDouble(Double.parseDouble(distance), "0.0"))
                .rotate(0)
                .position(point);

        mBaiduMap.addOverlay(textOption);

    }

    public void clearmarker_Seconds() {
        if (marker_Seconds.size() > 0) {
            try {
                for (Marker m : marker_Seconds) {
                    m.remove();
                }
            } catch (Exception e) {
            }
        }

        marker_Seconds.clear();

    }

    public void setPointClick(final int i) {
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                MyLog.L(MString.SUCCESSED + "点击=" + marker);
                if (marker_Seconds.size() >= 0) {
                    for (Marker m : marker_Seconds) {
                        if (marker == m) {
                            MyApp.isNewAdd=false;
                            Exploration exploration = FastJsonUtil.JsonToGetExplorInfo(m.getTitle());
                            MyApp.currExploration.setBean(exploration);
                            MyApp.BackActivity = i;
                            MyApp.currExploration.setPoint_type(projectType);
                            IntentToActivity.intent(MyApp.activity, SetPointInformationActivity.class);
                        }
                    }
                }
                return true;
            }
        });
    }

    public void setMCLICK(final Context context) {
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (markers.size() >= 0) {
                    for (Marker m : markers) {
                        if (marker == m) {
                            //designStage 设计阶段code
                            //弹出pop
                            InputUtil.closeInput((Activity) context);
                            WindowManager.LayoutParams params = ((Activity) context).getWindow().getAttributes();
                            params.alpha = 0.7f;
                            ((Activity) context).getWindow().setAttributes(params);

                            SearchProjectBean p = FastJsonUtil.JsonToGetSearchProject(m.getTitle());
                            String stage = p.getStage();
                            String stageids = p.getStage_ids();
                            if (stage.length() > 0) {
                                String[] stageName = stage.split(",");
                                String[] stageid = stageids.split(",");
                                List<SystemTypeBean> bean = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.designStage);
                                List<SystemTypeBean> mb = new ArrayList<SystemTypeBean>();
                                for (int i = 0; i < stageName.length; i++) {
                                    for (SystemTypeBean s : bean) {
                                        if (s.getTypecode().equals(stageName[i])) {
                                            mb.add(new SystemTypeBean(stageid[i], s.getTypename(), s.getTypecode()));
                                            break;
                                        }
                                    }
                                }
                                if (mb.size() > 0) {
                                    PopwindowUtil.popChoiceToActivity((Activity) context, mMapView, mb, m.getTitle());
                                } else {
                                    ToastShow.showShort(context, "阶段不存在！");
                                }


                            }

                        }
                    }
                }

                return true;
            }
        });
    }


    /**
     * 点位导航*
     */
    public void addMarka(final NavigationActivity activity, Exploration exploration, final LatLng point, final LatLng currentPt, SystemTypeBean systemTypeBean, final TextView view, final TextView title, boolean flag) {
        int image = Integer.parseInt(systemTypeBean.getTypecode());
        exploration.setIcon(image);
        exploration.setTypeName(systemTypeBean.getTypename());
        if (point == null) return;
        BitmapDescriptor b = BitmapDescriptorFactory.fromResource(image);
        bitmaps.add(b);
        OverlayOptions options = new MarkerOptions().position(point)
                .icon(b).anchor(0.5f, 0.5f);
        final Marker m = (Marker) mBaiduMap.addOverlay(options);
        m.setTitle(JSON.toJSONString(exploration));

        if (flag) {

            try {
                activity.updateWords(exploration.getTypeName() + "   " + exploration.getNumber(), (int) DistanceUtil.getDistance(point, currentPt));
            } catch (Exception e) {
            }
        }
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker == m && currentPt != null && point != null) {
                    Exploration exploration1 = FastJsonUtil.JsonToGetExplorInfo(marker.getTitle());
                    try {
                        view.setText("直线距离:");
                        SpannableString sp = new SpannableString(((int) DistanceUtil.getDistance(point, currentPt)) + "");
                        sp.setSpan(new ForegroundColorSpan(MyApp.activity.getResources().getColor(R.color.project_blue)), 0, sp.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                        view.append(sp);
                        SpannableString sp2 = new SpannableString("米");
                        sp.setSpan(new ForegroundColorSpan(MyApp.activity.getResources().getColor(R.color.bar_right)), 0, sp2.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                        view.append(sp2);
                        title.setText(exploration1.getTypeName() + "   " + exploration1.getNumber());
                        activity.updateLine(point, exploration1);
                    } catch (Exception e) {
                    }


                }
                return true;
            }
        });
    }


    public void onPause() {
        // MapView的生命周期与Activity同步，当activity挂起时需调用MapView.onPause()
        mMapView.onPause();

    }


    public void onResume() {
        // MapView的生命周期与Activity同步，当activity恢复时需调用MapView.onResume()
        mMapView.onResume();

    }

    public void onDestroy() {
        // MapView的生命周期与Activity同步，当activity销毁时需调用MapView.destroy()
        mMapView.onDestroy();

        // 回收 bitmap 资源
        for (BitmapDescriptor b : bitmaps) {
            try {
                b.recycle();
            } catch (Exception e) {
            }
        }


    }
}
